package com.qijia.travel.helper;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;


/**
 * 文件管理工具
 * @author Administrator
 *
 */
public class FileHelper {

	private FileHelper(){};
	
	/**
	 * 
	 * 方法描述：
	 * 删除指定文件
	 * 创建时间：Jan 26, 2010 7:50:38 PM 
	 * @param filepath	//文件路径
	 * @return	true:成功删除；false：删除失败
	 * @throws UtilsException 
	 */
	public static boolean deleteFile(String filePath) throws Exception{
		File file = new File(filePath);
		if(file.exists()&&file.isFile()){
			try {
				file.delete();
			} catch (Exception e) {
				throw new Exception("文件【filePath】无法删除！",e);
			}
			return true;
		}else{
			throw new Exception("文件【filePath】不存在或路径错误！");
		}
	}
	
	/**
	 * 
	 * 方法描述：
	 * 删除目录（文件夹）以及目录下的文件
	 * 创建时间：Jan 26, 2010 7:59:28 PM 
	 * @param dirPath	//文件夹路径
	 * @return	true：删除成功；false：删除失败
	 * @throws Exception 
	 */
	public static boolean deleteDirectory(String dirPath) throws Exception{
	    //如果dirPath不以文件分隔符结尾，自动添加文件分隔符   
	    if (!dirPath.endsWith(File.separator)) {   
	        dirPath = dirPath + File.separator;   
	    }   
	    File dirFile = new File(dirPath);   
	    //如果dir对应的文件不存在，或者不是一个目录，则退出   
	    if (!dirFile.exists() || !dirFile.isDirectory()) {   
	        return false;   
	    }   
	    
	    boolean flag = true;   
	    //删除文件夹下的所有文件(包括子目录)   
	    File[] files = dirFile.listFiles();   
	    for (int i = 0; i < files.length; i++) {   
	        //删除子文件   
	        if (files[i].isFile()) {   
	            flag = deleteFile(files[i].getAbsolutePath());   
	            if (!flag) break;   
	        } //删除子目录   
	        else {   
	            flag = deleteDirectory(files[i].getAbsolutePath());   
	            if (!flag) break;   
	        }   
	    }   
	    if (!flag) return false;   
	    //删除当前目录   
	    if (dirFile.delete()) {   
	        return true;   
	    } else {   
	        return false;   
	    }
	}
	
	/**
	 * 
	 * 方法描述：
	 * 创建文件夹
	 * 创建时间：May 27, 2010 11:22:57 PM 
	 * @param dirPath	//文件夹路径及名字
	 * @param override	//覆盖/不覆盖	true/false
	 * @throws Exception 
	 */
	public static String createDirectory(String dirPath, boolean override) throws Exception{
		File dir = new File(dirPath);
		if(dir.isDirectory()&&dir.exists()){
			if(override){
				//覆盖
				deleteDirectory(dirPath);
				try {
					dir.mkdirs();
				} catch (Exception e) {
					throw new Exception("创建文件夹【"+dirPath+"】失败！");
				}
				
			}else{
				//不覆盖
				return createDirectory(dirPath+"2",override);
			}
		}else{
			dir.mkdirs();
		}
		return dir.getAbsoluteFile().toString();
	}
	
    /**从文件中读取字符串
     * @param path
     * @return
     * @throws IOException
     */
    public static String readFile(String path) throws IOException{
        File file=new File(path);
        if(!file.exists()||file.isDirectory())
            throw new FileNotFoundException("无法读取文件，文件【"+path+"】不存在！");
        BufferedReader br=new BufferedReader(new FileReader(file));
        String temp=null;
        StringBuffer sb=new StringBuffer();
        temp=br.readLine();
        while(temp!=null){
            sb.append(temp+" ");
            temp=br.readLine();
        }
        br.close();
        return sb.toString();
    }
    
	/**
	 * 把字符串写入文件中
	 * @param str
	 * @param filePath
	 * @throws IOException
	 * @throws Exception 
	 */
	public static void writeFile(String str , String filePath) throws IOException, Exception {
		File file = new File(filePath);
		if (!file.exists()){
			try {
				file.createNewFile();
			} catch (Exception e) {
				throw new Exception("创建文件【"+filePath+"】失败！");
			}
		}
		
		FileOutputStream out = new FileOutputStream(file, true);
		StringBuffer sb = new StringBuffer();
		sb.append(str);
		out.write(sb.toString().getBytes("UTF-8"));
		out.close();
	}
	
	public static void writeFile(byte[] b, String filePath, String fileName) throws Exception{
		writeFile(b, filePath, fileName, false);
	}
	
	/**
	 * 
	 * 方法描述：
	 * 保存文件
	 * 创建时间：2011-2-21 下午09:28:35 
	 * @param b		文件字节
	 * @param filePath	文件保存路径
	 * @param fileName	文件名
	 * @param overlay	是否覆盖
	 * @throws Exception
	 */
	public static void writeFile(byte[] b, String filePath, String fileName, boolean overlay) throws Exception{
		
		if(b==null)
			return ;
		
		File file = new File(filePath+System.getProperty("file.separator")+fileName);
		if(file.exists() && !overlay){
			writeFile(b, filePath, fileName+"_2", overlay);
		}else{
			
	        FileOutputStream fos = new FileOutputStream(filePath+System.getProperty("file.separator")+fileName); // 上传到写死的上传路径
	        try {
				fos.write(b);  //写入文件
			} catch (Exception e) {
				throw e;
			}finally{
				fos.close();
			}		
			
		}
	}
	
	/**
	 * 
	 * 方法描述：
	 * 复制文件
	 * 创建时间：2011-2-22 下午02:37:41 
	 * @param inFile
	 * @param outFile
	 * @throws Exception
	 */
	public static void CopyFileByChannel(String inFile, String outFile)
			throws Exception {
		File in = new File(inFile);
		File out = new File(outFile);
		if(!in.exists() || !out.exists())return ;
		FileInputStream fin = new FileInputStream(in);
		FileOutputStream fout = new FileOutputStream(out);
		FileChannel inc = fin.getChannel();
		FileChannel outc = fout.getChannel();
		int bufferLen = 2097152;
		ByteBuffer bb = ByteBuffer.allocateDirect(bufferLen);
		while (true) {
			int ret = inc.read(bb);
			if (ret == -1) {
				fin.close();
				fout.flush();
				fout.close();
				break;
			}
			bb.flip();
			outc.write(bb);
			bb.clear();
		}
	}

}
